<template>
  <view class="coupon-page">
    <!-- 标签栏 -->
    <view class="tabs">
      <text
        v-for="(tab, idx) in tabs"
        :key="tab"
        class="tab"
        :class="{ active: activeTab === idx }"
        @click="changeTab(idx)"
      >{{ tab }}</text>
    </view>
    <!-- 优惠券列表 -->
    <view class="coupon-list">
      <template v-if="filteredCoupons && filteredCoupons.length > 0">
        <view
          class="coupon-card"
          v-for="(c, i) in filteredCoupons"
          :key="c.id || i"
          :class="{
            'coupon-used': c.status === 1,
            'coupon-expired': c.status === 2
          }"
        >
          <view class="coupon-inner" :class="{
            'inner-used': c.status === 1,
            'inner-expired': c.status === 2
          }">
            <view class="coupon-content">
              <view class="coupon-left">
				<view class="coupon-condition" :class="{'text-gray': c.status !== 0}">{{ c.condition }}</view>
                <view class="coupon-title" :class="{'text-gray': c.status !== 0}">仅限{{ c.title }}可用</view>
              </view>
              <view class="coupon-value">
                <text class="yuan" :class="{'text-gray': c.status !== 0}">¥</text>
                <text class="amount" :class="{'text-gray': c.status !== 0}">{{ c.value }}</text>
              </view>
            </view>
            <view class="coupon-divider"></view>
            <view class="coupon-footer">
              <text class="valid" :class="{'text-gray': c.status !== 0}">有效期至：{{ c.valid }}</text>
              <text class="use-btn" v-if="c.status === 0">去使用 ></text>
              <text class="use-btn text-gray" v-else>{{ c.status === 1 ? '已使用' : '已过期' }}</text>
            </view>
          </view>
        </view>
      </template>
      <template v-else>
        <!-- 添加空状态显示 -->
        <view class="coupon-empty-box">
          <image class="coupon-empty-img" src="/static/car1.png" mode="widthFix"></image>
          <view class="coupon-empty-text">暂无优惠券</view>
        </view>
      </template>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import baseUrl from '@/untils/urlConfig';
import request from '@/untils/request';

// ** 临时模拟本地存储的用户信息和 Token，用于测试 **
// ** 在实际应用中，请移除此段代码，改为用户登录成功后存储真实信息 **
uni.setStorageSync('userInfo', { userId: 1 });
uni.setStorageSync('token', 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6ImExY2Y2YzQ1LWQ3NGYtNDNhZC04Nzc2LTc5ZjVjZTYzYzJhNCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.sVcpT_LwYzWmTz2keOUxQnysqcNWp6nQ7gf3vdidU5Kc4kejJck3gtAjySJDDsGQfRbTP6O-1zMGX8MnxrWfdw'); // ** 替换为你的实际有效 token **
// ** 临时模拟本地存储结束 **

// 获取当前登录用户ID和token
const getCurrentUser = () => {
  const userInfo = uni.getStorageSync('userInfo');
  const token = uni.getStorageSync('token');
  if (!userInfo || !userInfo.userId || !token) {
    uni.showToast({
      title: '请先登录或检查本地存储',
      icon: 'none'
    });
    // 跳转到登录页面
    // setTimeout(() => {
    //   uni.navigateTo({
    //     url: '/pages/login/login'
    //   });
    // }, 1500);
    return null;
  }
  return { userId: userInfo.userId, token: token };
};

// 响应式数据
const tabs = ref(['待使用', '已使用', '已过期']);
const activeTab = ref(0);
const coupons = ref([]); // 将静态数据清空

// 格式化日期函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}.${month}.${day}`;
};

// 获取优惠券数据的方法
const fetchData = async () => {
  const user = getCurrentUser();
  if (!user) return; // 如果没有获取到用户（或 token），则不发送请求

  try {
    // 1. 调用用户优惠券中间表接口
    const userCouponResponse = await uni.request({
      url: baseUrl + '/chy/usercoupon/list', // 用户优惠券接口地址
      method: 'GET',
      data: {
        u_id: user.userId // 传递从 getCurrentUser 获取的真实（或模拟的）用户ID
        // 可能还需要分页等参数
      },
      header: {
        'Authorization': `Bearer ${user.token}` // 携带从 getCurrentUser 获取的 token
      }
    });

    if (userCouponResponse.statusCode === 200 && userCouponResponse.data && userCouponResponse.data.code === 200) {
      const userCoupons = userCouponResponse.data.rows || [];
      if (userCoupons.length === 0) {
        coupons.value = []; // 用户没有优惠券
        // uni.showToast({ title: '暂无优惠券', icon: 'none' });
        console.log('fetchData: User has no coupons.'); // 添加日志
        return;
      }

      // 提取优惠券ID列表
      const couponIds = userCoupons.map(uc => uc.cId); // 修改为提取 cId (大写 I)
      console.log('fetchData: User coupons fetched, c_ids:', couponIds); // 添加日志

      // 2. 调用优惠券详情接口
      // 注意：/coupon/list 接口接收 Coupon 对象作为参数，可能需要调整 data 参数的结构
      // 这里假设后端可以通过传递 c_id 列表来查询多条优惠券详情
      const couponDetailsResponse = await uni.request({
        url: baseUrl + '/chy/coupon/list', // 优惠券详情接口地址
        method: 'GET',
        data: {
          ids: couponIds.join(',') // 假设后端可以通过逗号分隔的ids字符串查询
          // 或者如果后端支持数组：ids: couponIds
          // 或者循环调用 /coupon/{id} 接口 (效率较低)
        },
        header: {
          'Authorization': `Bearer ${user.token}` // 携带从 getCurrentUser 获取的 token
        }
      });

      if (couponDetailsResponse.statusCode === 200 && couponDetailsResponse.data && couponDetailsResponse.data.code === 200) {
        const couponDetails = couponDetailsResponse.data.rows || [];
        console.log('fetchData: Coupon details fetched:', couponDetails); // 添加日志

        // 3. 整合数据
        const combinedCoupons = userCoupons.map(uc => {
          // 使用 uc.cId (大写 I) 来匹配 couponDetails 中的 id
          const detail = couponDetails.find(cd => cd.id === uc.cId);
          if (detail) {
            // 打印原始中间表和详情数据，方便对比
            console.log('Mapping userCoupon:', uc, 'with couponDetail:', detail); // 添加日志
            return {
              id: uc.cId, // 使用中间表的 cId 作为优惠券的唯一标识（如果需要）
              title: detail.name, // 优惠券名称
              condition: '满' + detail.size + '元可用', // 使用门槛
              value: detail.discount, // 优惠金额
              valid: `${formatDate(detail.expirationStart)}—${formatDate(detail.expirationEnd)}`, // 有效期
              status: uc.status // 使用中间表的状态 (0:待使用 1:已使用 2:已过期)
              // 保留其他可能需要的字段，比如数量 num: uc.num
            };
          } else {
            console.warn('fetchData: Could not find coupon detail for c_id:', uc.cId); // 添加警告日志
            return null; // 如果找不到详情，可以跳过或标记错误
          }
        }).filter(Boolean); // 过滤掉找不到详情的项

        coupons.value = combinedCoupons;
        console.log('fetchData: Final coupons.value:', coupons.value); // 添加日志
        // uni.showToast({ title: '获取优惠券数据成功', icon: 'success' });

      } else {
        const errorMessage = couponDetailsResponse.data && couponDetailsResponse.data.msg ? couponDetailsResponse.data.msg : '获取优惠券详情失败';
        uni.showToast({ title: errorMessage, icon: 'none' });
        console.error('获取优惠券详情失败:', couponDetailsResponse); // 添加日志
        coupons.value = []; // 清空数据
      }

    } else {
      const errorMessage = userCouponResponse.data && userCouponResponse.data.msg ? userCouponResponse.data.msg : '获取用户优惠券列表失败';
      uni.showToast({ title: errorMessage, icon: 'none' });
      console.error('获取用户优惠券列表失败:', userCouponResponse); // 添加日志
      coupons.value = []; // 清空数据
    }

  } catch (error) {
    console.error('请求失败:', error); // 添加日志
    uni.showToast({ title: '网络请求失败', icon: 'none' });
    coupons.value = []; // 清空数据
  }
};

// 页面加载时获取数据
onMounted(() => {
  console.log('onMounted: calling fetchData'); // 添加日志
  fetchData();
});

// 计算属性：过滤优惠券列表
const filteredCoupons = computed(() => {
  console.log('filteredCoupons computed:', 'activeTab=', activeTab.value, 'coupons.value=', coupons.value); // 添加日志
  // 确保 coupons.value 是一个数组且不为 null/undefined
  if (!Array.isArray(coupons.value)) {
    console.log('filteredCoupons computed: coupons.value is not an array'); // 添加日志
    return [];
  }
  const filtered = coupons.value.filter(c => {
    console.log('Filtering coupon:', c, 'with status:', c.status, 'against activeTab:', activeTab.value); // 添加日志
    return c.status === activeTab.value;
  });
  console.log('filteredCoupons computed: Filtered result:', filtered); // 添加日志
  return filtered;
});

// 切换标签栏方法
const changeTab = (idx) => {
  activeTab.value = idx;
  console.log('changeTab called, new activeTab:', activeTab.value); // 添加日志
};

// 领取优惠券方法 (目前只更新本地状态，如需调用后端接口，需另行实现)
// const receiveCoupon = (i) => {
//   if (coupons.value[i].status === 0) {
//     // TODO: 调用后端领取优惠券接口
//     // ...
//     coupons.value[i].status = 1; // 暂时只更新本地状态
//   }
// };

</script>

<style>
	.coupon-page {
		background: #fafafa;
		min-height: 100vh;
		font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
	}
	.tabs {
		display: flex;
		justify-content: center;
		align-items: center;
		background: #238aff;
		padding-bottom: 0;
		margin-bottom: 20rpx;
		height: 70rpx;
	}
	.tab {
		color: #b3d2ff;
		font-size: 32rpx;
		margin: 0 60rpx;
		padding-bottom: 10rpx;
		border-bottom: 0;
		font-weight: 500;
		position: relative;
	}
	.tab.active {
		color: #fff;
		font-weight: bold;
	}
	.tab.active::after {
		content: '';
		display: block;
		margin: 0 auto;
		margin-top: 8rpx;
		width: 44rpx;
		height: 3rpx;
		background: #fff;
		border-radius: 2rpx;
	}
	.coupon-list {
		margin: 0;
		padding: 0 0 0 0;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.coupon-card {
		width: 92vw;
		max-width: 700rpx;
		background: #fff;
		border-radius: 36rpx;
		margin-bottom: 36rpx;
		box-shadow: 0 8rpx 32rpx rgba(255, 140, 96, 0.10);
		position: relative;
		padding: 0;
		overflow: visible;
	}
	.coupon-inner {
		background: linear-gradient(90deg, #ff8b5f 0%, #ff6a2f 100%);
		border-radius: 28rpx;
		margin: 0;
		margin-left: 24rpx;
		margin-right: 24rpx;
		margin-top: 5rpx;
		margin-bottom: -10rpx;
		padding: 36rpx 36rpx 18rpx 36rpx;
		position: relative;
		z-index: 1;
	}
	.coupon-content {
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
	}
	.coupon-left {
		flex: 1;
		min-width: 0;
		margin-right: 24rpx;
		display: flex;
		flex-direction: column;
	}
	.coupon-title {
		font-size: 24rpx;
		margin-bottom: 10rpx;
		opacity: 0.95;
		color: #fff;
	}
	.coupon-condition {
		font-size: 36rpx;
		font-weight: bold;
		color: #fff;
	}
	.coupon-value {
		display: flex;
		align-items: flex-end;
		min-width: 120rpx;
		margin-left: 16rpx;
		margin-bottom: 2rpx;
	}
	.coupon-value .yuan {
		font-size: 28rpx;
		margin-right: 4rpx;
		color: #fff;
		line-height: 1.1;
	}
	.coupon-value .amount {
		font-size: 64rpx;
		font-weight: bold;
		color: #fff;
		line-height: 1;
	}
	.coupon-divider {
		width: 100%;
		height: 0;
		border-bottom: 2rpx dashed rgba(255,255,255,0.5);
		margin: 18rpx 0 0 0;
	}
	.coupon-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 18rpx;
		font-size: 22rpx;
		opacity: 0.95;
		color: #fff;
	}
	.use-btn {
		color: #fff;
		background: rgba(255,255,255,0.18);
		border-radius: 24rpx;
		padding: 6rpx 28rpx;
		font-size: 26rpx;
		font-weight: 500;
	}
	.coupon-card::before,
	.coupon-card::after {
		content: '';
		position: absolute;
		width: 36rpx;
		height: 72rpx;
		background: #fafafa;
		border-radius: 50%;
		top: 50%;
		transform: translateY(-50%);
		z-index: 2;
	}
	.coupon-card::before {
		left: -18rpx;
	}
	.coupon-card::after {
		right: -18rpx;
	}
	.coupon-card.coupon-used,
	.coupon-card.coupon-expired {
		background: #f7f7f7;
		box-shadow: 0 8rpx 32rpx rgba(220,220,220,0.10);
	}
	.coupon-inner.inner-used,
	.coupon-inner.inner-expired {
		background: #fff;
	}

  /* 灰色文本 */
  .text-gray {
    color: #b0b0b0 !important;
  }


/* 空状态样式 */
.coupon-empty-box {
  background: #fff;
  border-radius: 32rpx;
  margin: 40rpx 16rpx 0 16rpx;
  padding: 120rpx 0 120rpx 0;
  box-shadow: 0 8rpx 32rpx rgba(35,138,255,0.04);
  display: flex;
  flex-direction: column;
  align-items: center;
}
.coupon-empty-img {
  width: 650rpx;
  opacity: 0.25;
  margin-bottom: 32rpx;
}

.coupon-empty-text {
  color: #bbb;
  font-size: 30rpx;
  margin-top: 12rpx;
}
</style>
